package com.heima.user.service.impl;

import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class ApUserRelationServiceImpl implements ApUserRelationService {

    private final RedisTemplate redisTemplate;

    private final CacheService cacheService;
    /**
     * 关注或取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.参数校验
        if (dto == null || dto.getOperation() == null || dto.getOperation() >1 || dto.getOperation() <0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();
        //3 关注 apuser:follow:  apuser:fans:
        Integer authorId = dto.getAuthorId();
        if (dto.getOperation() == 0){
            //将对方写入我的关注中
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, String.valueOf(authorId), System.currentTimeMillis());
            //将我写入对方的粉丝中
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + authorId, String.valueOf(userId), System.currentTimeMillis());
        }else {
            //将对方从我的关注中移除
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, String.valueOf(authorId));
            //将我从对方的粉丝中移除
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + authorId, String.valueOf(userId));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
